package com.sq.partner.manager.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.GatewayCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.CommamtFee;
import com.sq.partner.manager.mybatis.model.FacadePayment;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.service.ExternalPaymentCardService;
import com.sq.partner.manager.service.OutboundCardApplyService;
import com.sq.partner.manager.service.PayService;
import com.sq.partner.manager.util.DateUtil;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.MD5Util;
import com.sq.partner.manager.util.StrUtil;


/**
 *
 * @author zsm 2018年7月18日
 *
 */
@Controller
@RequestMapping("/outboundCard")
public class PayController {
	
	private static Logger logger = LogUtil.getLog(PayController.class);
	
	@Resource
	private OutboundCardApplyService outboundCardApplyService;
	@Resource
	private PayService payService;
    @Resource
    private ExternalPaymentCardService cardService;
	
	/**
	 * 出库缴费
	 * @param session
	 * @param commamtId
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/cardPay")
	public String payTheFees(HttpSession session,String commamtId,ModelMap model)throws Exception{
		GatewayUser gatewayuser=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		CommamtFee commamtFee = outboundCardApplyService.queryForPay(commamtId);
		//获取合作验证码
		String verificationCode = GatewayCache.getCache(Constants.FACADE_PAYMENT_KEY);
		HashMap<String,String> map=new HashMap<String,String>();
		map.put("payId", commamtId);
		FacadePayment payment=outboundCardApplyService.queryPayment(map);
		if(null==payment){
		    //保存payment
		    //新增
	        payment = outboundCardApplyService.saveFacadePayment(commamtFee,gatewayuser);
		}else{
		    //如果是待支付
		    if(Constants.PAYMENT_STATUS_1.equals(payment.getStatus())){
		        //调用支付平台查询接口看是否支付完成
		        payment=payService.noPaymentStatusForOut(payment);
		        //如果支付平台接口查询为支付成功
		        if("2".equals(payment.getStatus())){
		            //更新出库表
		            payService.updatCommamtInfo(payment.getPayId(),
                            commamtFee.getStatus(),
                            Constants.ACTIR_CARD_OUTBOUND_PAY);
                    // TODO 调用收付缴费接口
		            Result result = cardService.cardPayToPayment(payment,
		                    gatewayuser.getEmployeeNo(), gatewayuser.getUserCode());
		            if ("success".equals(result.getResult())) {
		                //更新卡单表
		                payService.updateStatusByCommamtId(payment.getPayId(),
		                        Constants.ACTIR_CARD_RELATION,
		                        Constants.ACTIR_CARD_ACTIVABLE);
		            }
//                    //出库缴费成功，回写卡单表状态，和出库费用表状态
//                    outboundCardApplyService.doConfirm(payment.getPayId(), commamtFee.getIsPreFee(),
//                            commamtFee.getStatus(), "0000", payment.getTransNo());
		            //返回成功页面
		            return "/actirationCard/activatedCard/pay/success";
		        }
		    }
		    //如果支付完成则更新出库信息为已缴费
		    else if(Constants.PAYMENT_STATUS_2.equals(payment.getStatus())){
		        //更新出库表
                payService.updatCommamtInfo(payment.getPayId(),
                        commamtFee.getStatus(),
                        Constants.ACTIR_CARD_OUTBOUND_PAY);
                // TODO 调用收付缴费接口
                Result result = cardService.cardPayToPayment(payment, 
                        gatewayuser.getEmployeeNo(),gatewayuser.getUserCode());
                if ("success".equals(result.getResult())) {
                    //更新卡单表
                    payService.updateStatusByCommamtId(payment.getPayId(),
                            Constants.ACTIR_CARD_RELATION,
                            Constants.ACTIR_CARD_ACTIVABLE);
                }
//		        //更新出库信息
//                //出库缴费成功，回写卡单表状态，和出库费用表状态
//                outboundCardApplyService.doConfirm(payment.getPayId(), commamtFee.getIsPreFee(),
//                        commamtFee.getStatus(), payment.getPayResult(), payment.getTransNo());
		        //返回成功页面
		        return "/actirationCard/activatedCard/pay/success";
		    }
		    //如果是支付失败，则重新支付
		    else if(Constants.PAYMENT_STATUS_3.equals(payment.getStatus())){
		        
		    }
		    //服务器忙
		    else if(Constants.PAYMENT_STATUS_4.equals(payment.getStatus())){
		        return "/actirationCard/activatedCard/pay/serviceBusy";
		    }
		}
		//校验字符串
		String transDate = DateUtil.format(payment.getTransDate(), "yyyy-MM-dd HH:mm:ss");
        String transDatestr = transDate.replaceAll("\\D", "");
		String checkStr=verificationCode
                +"comCode="+payment.getComCode()
                +"&payID="+payment.getPayId()
                +"&requestCode="+Config.getProp("life.pay.requestCode")
                +"&transAmt="+payment.getTransAmt()
                +"&transDate="+transDatestr
                +"&transNo="+payment.getTransNo();
        logger.debug("支付checkStr:" + checkStr);
        String checkValue = MD5Util.md5One(checkStr).toLowerCase();
		model.put("payUrl",Config.getProp("life.pay.payUrl"));
		model.put("transNo",payment.getTransNo());
		model.put("transDate",transDate);
		model.put("requestCode",payment.getRequestCode());
		model.put("comCode",payment.getComCode());
		model.put("payID",payment.getPayId());
		model.put("transAmt",payment.getTransAmt());
		model.put("payName",payment.getPayName());
		model.put("pageRetUrl",null);
		model.put("bgRetUrl",Config.getProp("life.callback.bgRetUrl"));
		model.put("remark",null);
		model.put("checkValue",checkValue);
		return "/actirationCard/pay/payment";
	}
	@RequestMapping(value = "/doConfirm")
    public String payConfirm(ModelMap model,String comCode,String merId,String payAmt,String payDate,String payID,String paymentType,String payNo,String payResult,
			String requestCode,String transDate,String transNo,String checkValue,String payRemark,HttpSession session)
            throws Exception {
	    // 获取合作验证码
        String verificationCode = GatewayCache.getCache(Constants.FACADE_PAYMENT_KEY);
        if (StrUtil.isEmpty(verificationCode)) {
            verificationCode = "";
        }
        FacadePayment facadepayment=outboundCardApplyService.getFacadePaymentByTransNo(transNo);//查询支付表是否有支付成功或处理中状态记录
        if(facadepayment!=null){
            String status=facadepayment.getStatus();
            if(Constants.PAYMENT_STATUS_2.equals(status)){
                //TODO 调用缴费收付接口
//                cardService.cardPayToPayment(facadepayment, gatewayuser.getEmployeeNo());
                model.put("status", "success");
                return "/actirationCard/activatedCard/pay/callBack";
            }
        }
      //如果支付状态是1未支付或3支付失败状态则继续向下执行
        String payDateStr = payDate != null ? payDate.replaceAll("\\D", "") : null;
        String transDateStr = transDate != null ? transDate.replaceAll("\\D", "") : null;
        String checkStr = verificationCode + "comCode=" + comCode + "&merId=" + merId + "&payAmt=" + payAmt + "&payDate=" + payDateStr + "&payID=" + payID
                +"&payNo="+payNo+"&payResult="+payResult+"&paymentType="+paymentType+"&requestCode="+requestCode
                +"&transDate="+transDateStr+"&transNo="+transNo; 
        try {
         // 检验参数是否正确
            if (checkValue.equals(MD5Util.md5One(checkStr).toLowerCase())) {
             // 支付回调，更新T_FACADE_PAYMENT（支付信息表）相关信息
                FacadePayment payment = new FacadePayment();
                payment.setTransNo(transNo);
                payment.setMerId(merId);
                payment.setPayNo(payNo);
                payment.setPayId(payID);
                payment.setPaymentType(paymentType);
                payment.setPayDate(DateUtil.parse(payDate, "yyyy-MM-dd HH:mm:ss"));
                payment.setPayResult(payResult);
                payment.setPayRemark(payRemark);
                payment.setFeedbackDate(new Date());
                payment.setTransAmt(new BigDecimal(payAmt));
                payment.setUserCode(facadepayment.getUserCode());
                if ("0000".equals(payResult)) {
                    payment.setStatus("2");// 支付成功
                    //更新支付表状态
                    outboundCardApplyService.updateFacadePayMent(payment);
                    //更新出库表
                    payService.updatCommamtInfo(payID,
                            Constants.ACTIR_CARD_OUTBOUND_NOPAY,
                            Constants.ACTIR_CARD_OUTBOUND_PAY);
                    Map<String, String> reMap = payService.getEmployeeNoByCommamtId(payID);
                    // TODO 调用收付缴费接口
                    HashMap<String,String> map=new HashMap<String,String>();
                    map.put("payId", payID);
                    payment=outboundCardApplyService.queryPayment(map);
                    Result result = cardService.cardPayToPayment(payment,
                            reMap.get("EMPLOYEE_NO"),reMap.get("USER_CODE"));
                    if ("success".equals(result.getResult())) {
                        //更新卡单表
                        payService.updateStatusByCommamtId(payment.getPayId(),
                                Constants.ACTIR_CARD_RELATION,
                                Constants.ACTIR_CARD_ACTIVABLE);
                        model.put("status", "success");
                    }
//                    //出库缴费成功，回写卡单表状态，和出库费用表状态
//                    outboundCardApplyService.doConfirm(payID, commamtFee.getIsPreFee(),
//                            commamtFee.getStatus(), payResult, transNo);
                } else {
                    payment.setStatus("3");// 支付失败
                    //更新支付表状态
                    outboundCardApplyService.updateFacadePayMent(payment);
                }
                model.put("status", "success");
            }else{
                logger.info("交易流水号:" + transNo + "校验失败");
                model.put("status", "error");
            }
        } catch (Exception e) {
            logger.error(e);
            model.put("status", "error");
        }
        return "/actirationCard/activatedCard/pay/callBack";
    }
}
